package com.joesem.sale.client.widget

import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.graphics.flatten


class PaintView : View {

    private val paint = Paint()
    private var isPaint = false

    init {
        paint.color = Color.BLACK
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = dp2px(5f).toFloat()
        paint.isAntiAlias = true
        paint.strokeCap = Paint.Cap.ROUND
        paint.strokeJoin = Paint.Join.ROUND
    }

    constructor(context: Context) : super(context)

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (isPaint) {
            canvas?.drawPath(path, paint)
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        setBackgroundColor(Color.WHITE)
    }

    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
        parent.requestDisallowInterceptTouchEvent(isPaint)
        return super.dispatchTouchEvent(event)
    }

    private val path = Path()
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                path.moveTo(event.x, event.y)
            }

            MotionEvent.ACTION_MOVE -> {
                path.lineTo(event.x, event.y)
                invalidate()
            }

        }
        return true
    }

    private fun dp2px(dpValue: Float): Int {
        val scale = Resources.getSystem().displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    fun isPaintComplete(): Boolean {
        return (path.flatten().toMutableList().size >= 20)
    }

    fun getPaintBitmap(): Bitmap {
        isDrawingCacheEnabled = true
        val bitmap = Bitmap.createBitmap(this.drawingCache)
        isDrawingCacheEnabled = false
        return bitmap
    }

    fun isPaint(start: Boolean) {
        isPaint = start
    }

    fun paintColor(color: Int) {
        paint.color = color
    }

    fun paintWidth(width: Float) {
        paint.strokeWidth = width
    }

    fun clear() {
        path.reset()
        invalidate()
    }
}